<template>
  <div ref="chart-cpu" class="cpu_container" style="width: 90% ;height: 90%" />
</template>

<script>
import * as echarts from 'echarts'
import { getCupByIp } from '@/api/chart'
import { formatDate } from '@/utils/index.js'
export default {
  props: ['ip'],
  data() {
    return {
      cupData: {
        xAxisData: [],
        seriesData: []
      },
      intervalId: null// 存储定时器的ID
    }
  },
  mounted() {
    this.fetchCupData() // 首次获取数据并创建图表
    this.intervalId = setInterval(this.fetchCupData, 1000)
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId)
    }
  },
  methods: {
    formatDate,
    async fetchCupData() {
      console.log('主机名:', this.ip)
      const response = await getCupByIp(this.ip)
      const mainHost = response[0]
      this.cupData.xAxisData = mainHost.map((item) =>
        formatDate(item.createTime)
      )
      this.cupData.seriesData = mainHost.map((item) => item.sys)
      this.createChartCpu() // 使用获取到的数据创建图表
    },
    createChartCpu() {
      var myChart = echarts.init(this.$refs['chart-cpu'])
      var option = {
        title: {
          text: 'CPU'
        },
        tooltip: {},
        xAxis: {
          axisLabel: {
            // 旋转标签（45度或更多）
            rotate: 30
            // 格式化函数
          },
          data: this.cupData.xAxisData,
          name: '日期'
        },
        yAxis: {
          name: 'CPU利用率',
          axisLabel: {
            formatter: '{value} %'
          }
        },
        series: [
          {
            name: 'CPU利用率',
            type: 'line',
            smooth: true,
            lineStyle: {
              color: '#4BAAF4'// 线的颜色
            },
            itemStyle: {
              color: '#36A8FF' // 折点颜色
            },
            emphasis: {
              areaStyle: {
                color: '#B1DAFA'
              }
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: '#B1DAFA' // 0% 处的颜色 B1DAFA
                  },
                  {
                    offset: 1,
                    color: '#F2F9FE' // 100% 处的颜色
                  }
                ],
                false
              )
            },
            data: this.cupData.seriesData
          }
        ]
      }
      myChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped></style>
